/*
 * @Author: 火红色祥云 809880192@qq.com
 * @Date: 2023-09-06 20:30:12
 * @LastEditors: 火红色祥云 809880192@qq.com
 * @LastEditTime: 2023-09-25 21:22:54
 * @FilePath: /imx6ull-app/23_uart/main.c
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <stdio.h>
#include <pthread.h>

#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
       
#include "./uart.h"

#if 0
#define DEV_UART    "/dev/ttymxc2"
#else
#define DEV_UART    "/dev/pts/2"
#endif

void *SendThread(void *args)
{
    char send_buffer[] = {0x7d,0x7b,0x01,0xAA,0x01,0xBB,0x00,0x05,0x01,0x02,0x03,0x04,0x05,0x12,0x34,0x7d,0x7d};

    int *fd = (int *)args;

    while (1)
    {
        // 向串口发送数据
        uart_send(fd[0], send_buffer, sizeof(send_buffer));
        sleep(1);
    }
}

void *RecvThread(void *args)
{
    int *fd = (int *)args;
    char recv_buffer[255];
    fd_set read_fds;
    FD_ZERO(&read_fds);
    FD_SET(fd[0],&read_fds);
    while (1)
    {
        select(fd[0]+1,&read_fds,NULL,NULL,NULL);
        if (FD_ISSET(fd[0],&read_fds))
        {
            uart_recv(fd[0],recv_buffer,sizeof(recv_buffer));
        }
        
    }
    
}

int main()
{
    int fd;
    
    pthread_t SendHandle;
    pthread_t RecvHandle;

    // 初始化串口
    fd = uart_init(DEV_UART);
    if (fd == -1) {
        return -1;
    }
    
    pthread_create(&SendHandle,NULL,SendThread,&fd);
    pthread_detach(SendHandle);

    pthread_create(&RecvHandle,NULL,RecvThread,&fd);
    pthread_detach(RecvHandle);
    
    while (1);
    
    // 关闭串口设备文件
    close(fd);
    
    return 0;
}
